const axios = require('../config/request')
const cheer = require('cheerio')

/**
 * 每次下载前获取一次session, 然后搜索、保存、下载
 * 搜索可以不要session, 保存一定要带session, 下载暂未测试
 */
async function getCookie (uid) {
  const res = await axios.get('http://cn.epubee.com/', {
    headers: {
      Cookie: `identify=${uid};`
    }
  })
  // console.log(res.headers)
  return res.headers['set-cookie'][0]
}

async function genidWithLocalid () {
  const res = await axios.post(`http://cn.epubee.com/keys/genid_with_localid.asmx/genid_with_localid`, {
    localid: ''
  })
  return res.data.d[0]['ID']
}

async function getSearchList (skey) {
  return axios.post('http://cn.epubee.com/keys/get_ebook_list_search.asmx/getSearchList', {
    skey
  })
}

async function onlineAddBook (bookid, uid) {
  return axios.post('http://cn.epubee.com/app_books/addbook.asmx/online_addbook', {
    bookid,
    uid,
    act: 'add'
  }, {
    headers: {
      Accept: 'application/json, text/javascript, */*; q=0.01',
      'Accept-Encoding': 'gzip, deflate',
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
    }
  })
}

async function getEBookList (uid) {
  return axios.get('http://cn.epubee.com/files.aspx', {
    transformResponse: [
      (data) => {
        const $ = cheer.load(data)
        const contents = $('.listEbook .contentshow')
        const list = []
        for (let i = 0; i < contents.length; i++) {
          const title = $(`#gvBooks_lblTitle_${i}`).text()
          const bid = $(`#gvBooks_gvBooks_child_${i}_hpdownload_0`).attr('target')
          list.push({
            title,
            bid
          })
        }
        return list
      }
    ],
    headers: {
      Cookie: `identify=${uid};`
    }
  })
}

async function getKey (uid, strbid) {
  return axios.post('http://cn.epubee.com/app_books/click_key.asmx/getkey', {
    isVip: 0,
    uid,
    strbid
  })
}

async function deleteMyBooks (uid, bids) {
  return axios.post('http://cn.epubee.com/app_books/deletemybooks.asmx/deletemybooks', {
    uid,
    bids // 最前面一个0, 其余以英文逗号分隔
    // bids:'0,qiEzfHwXgRIxmxaRo6At%2b1x%2bJXRFh0CXUIE3T3JgcMJ3DeKd7eJ3MfNibVmJHSG6f5sOeod8GVV4b3D2RAqsPy2WNu0b2vZxLWbrWUIc1ZbIPFzGUlGA7h2uQvMJ4BR3AZz0joNjlvQ%3d,JzOavJf0v%2btEBNidu7ZVLf%2fQ4DowCrLYADSXiFLGmWegFZjXd6KuFeLhNXsQjnQ%2bPgNHsvWgA6MJFifXAs8TOCNlBm6CQ7%2bLH9ZG8ihElJuR3yd2q73MfV%2bU%2bKMl1oVoF3peqJwKseI%3d'
  })
}

async function login (uid) {
  const res = await axios.get('http://cn.epubee.com/files.aspx')
  let cookies = ''
  res.headers['set-cookie'].forEach(item => {
    const c = item.substring(0, item.lastIndexOf('; path'))
    cookies = cookies + c + '; '
  })
  // console.log(cookies)
  await axios.post('http://cn.epubee.com/keys/retrieve_cloud_id.asmx/Retrieve', {
    eID: '26656013',
    userpassword: 'epubeecn'
  }, {
    headers: {
      Cookie: cookies
    }
  })
  return cookies.replace('identify=0;', `identify=${uid};`)
}

async function download (bid, uid, key) {
  return axios.get(`http://files.epubee.com/getFile.ashx?bid=${bid}&uid=${uid}&t_key=${key}`, {
    responseType: 'arraybuffer',
    timeout: 1000 * 60 * 20
  })
}

// login().then((c) => {console.log(c)})

// let item = 'ASP.NET_SessionId=ejmlp442o2x2ozksq4zkjgvi; path=/; HttpOnly'
// console.log(item.substring(0, item.lastIndexOf('; path')))

module.exports = {
  genidWithLocalid,
  getKey,
  getSearchList,
  onlineAddBook,
  getEBookList,
  deleteMyBooks,
  getCookie,
  login,
  download
}
